/**
 * 条码解析器
 * @author HexPang 2017-04-27
 */
// 配置规则
// var parserConfig = [
//     {
//         name:"条码1",
//         size:12,//条码长度
//         startWith:'1003',//开头匹配
//         endWith:'0500',//结尾匹配
//         regExp:'[0-9]',//正则匹配
//         elements:[
//             {
//                 name:"product_code", //产品编码
//                 range:[0,4], //0到4位,
//                 unit:["千克",1000]
//             },{
//                 name:"weight",
//                 range:[5,8]，
//                 unit:"克"
//             }
//         ]
//     }
// ];
var config = null;
var parser = {
    parse : function(code){
        var result = null;

        if(config == null){
            throw "Parser need config.";
            return null;
        }

        for(var i in config){
            var conf = config[i];
            var match = false;
            if(conf.size != undefined && conf.size == code.length){
                match = true;
            }
            if(conf.startWith != undefined){
                match = false;
                if(code.substr(0,conf.startWith.length) == conf.startWith){
                    match = true;
                }else{
                    match = false;
                }
            }
            if(conf.endWith != undefined){
                if(code.substr(code.length - conf.endWith.length,conf.endWith.length) == conf.endWith){
                    match = true;
                }else{
                    match = false;
                }
            }
            if(conf.regEx != undefined){
                var pat = new RegExp(conf.regEx);
                if(!pat.test(code)){
                    match = false;
                }else{
                    match = true;
                }
            }
            if(match){
                var result = {};
                result["name"] = conf.name;
                for(var j in conf.elements){
                    var element = conf.elements[j];
                    result[element.name] = code.substr(element.range[0],element.range[1]);
                    if(element.unit != undefined){
                        if(typeof element.unit == "string"){
                            result[element.name] += element.unit;
                        }else if(typeof element.unit == "object"){
                            result[element.name] = result[element.name] / element.unit[1] + element.unit[0];
                        }
                    }
                }
            }
        }
        return result;
    },
    setConfig : function(conf){
        config = conf;
    }
}
